package com.example.service;

import com.example.elasticsearch.data.User;
import com.example.elasticsearch.repository.ESUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
public class ESUserService {

    @Autowired
    private ESUserRepository esUserRepository;

    public User saveUser(User user) {
        // 保存用户到 Elasticsearch 索引中
        return esUserRepository.save(user);
    }

    public List<User> getAllUsers(int page, int size) {
        Iterable<User> usersIterable = esUserRepository.findAll();
        return StreamSupport.stream(usersIterable.spliterator(), false)
                .collect(Collectors.toList());
    }

    public Optional<User> getUserById(Long id) {
        // 根据 ID 查询用户
        return esUserRepository.findById(id);
    }

    public List<User> findByUsername(String username) {
        // 根据用户名查询用户
        return esUserRepository.findByUsername(username);
    }
}
